module PcrWebApps
  module Webs
    def self.included(base)
      base.extend ClassMethods
    end

    module ClassMethods
      def has_url(options = {})
        configuration = { :field_name => :url,
                          :force => false}
        configuration.update(options) if options.is_a?(Hash)
        text =  ""
        text +=  "validates_presence_of :#{configuration[:field_name]}" if configuration[:force]
        text += <<-DELIM
          validates_format_of :#{configuration[:field_name]}, 
            :with => /^((http|https):\\/\\/)[a-z0-9]+([\\-\\.]{1}[a-z0-9]+)*\\.[a-z]{2,5}(([0-9]{1,5})?\\/.*)?$/,
            :allow_blank => true,
            :message => "is not a valid url"
          before_validation :add_protocol
          private
          def add_protocol
            url_value = self["#{configuration[:field_name]}"]
            self["#{configuration[:field_name]}"] = "http://" + url_value unless /^(http|https):\\/\\// =~ url_value || url_value.blank?
          end
        DELIM
        class_eval text
      end
    end
  end
end
